<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 返回登录页 -->
      <div class="back-home">
        <el-button type="text" @click="goBack">
          <iconify-icon icon="mdi:arrow-left" width="20" height="20"></iconify-icon>
          返回登录
        </el-button>
      </div>

      <div class="login-header">
        <h2>忘记密码</h2>
        <p>Forgot Password</p>
      </div>

      <!-- 步骤指示器 -->
      <div class="steps-container">
        <el-steps :active="currentStep" finish-status="success" simple>
          <el-step title="身份验证" />
          <el-step title="重置密码" />
        </el-steps>
      </div>

      <!-- 步骤1：身份验证 -->
      <div v-if="currentStep === 0" class="step-content">
        <el-form
          ref="verifyFormRef"
          :model="verifyForm"
          :rules="verifyRules"
          class="login-form"
          @submit.prevent="handleVerify"
        >
          <el-form-item prop="username">
            <el-input
              v-model="verifyForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              size="large"
              clearable
              @keyup.enter="handleVerify"
            />
          </el-form-item>

          <el-form-item prop="question">
            <el-select
              v-model="verifyForm.question"
              placeholder="请选择安全问题"
              prefix-icon="QuestionFilled"
              size="large"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in securityQuestions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item prop="answer">
            <el-input
              v-model="verifyForm.answer"
              placeholder="请输入安全问题的答案"
              prefix-icon="Key"
              size="large"
              clearable
              @keyup.enter="handleVerify"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="login-button"
              :loading="loading"
              @click="handleVerify"
            >
              {{ loading ? '验证中...' : '下一步' }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤2：重置密码 -->
      <div v-if="currentStep === 1" class="step-content">
        <el-form
          ref="resetFormRef"
          :model="resetForm"
          :rules="resetRules"
          class="login-form"
          @submit.prevent="handleReset"
        >
          <el-form-item prop="newPassword">
            <el-input
              v-model="resetForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              prefix-icon="Lock"
              size="large"
              show-password
              clearable
              @keyup.enter="handleReset"
            />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
              v-model="resetForm.confirmPassword"
              type="password"
              placeholder="请确认新密码"
              prefix-icon="Lock"
              size="large"
              show-password
              clearable
              @keyup.enter="handleReset"
            />
          </el-form-item>

          <el-form-item>
            <div class="button-group">
              <el-button
                size="large"
                class="back-button"
                @click="goBackStep"
              >
                上一步
              </el-button>
              <el-button
                type="primary"
                size="large"
                class="login-button"
                :loading="loading"
                @click="handleReset"
              >
                {{ loading ? '重置中...' : '重置密码' }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <!-- 用户信息确认 -->
      <div v-if="verifiedUser" class="user-info">
        <el-alert
          title="用户信息确认"
          type="success"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>用户名：{{ verifiedUser.username }}</p>
            <p>真实姓名：{{ verifiedUser.realName }}</p>
            <p>角色：{{ verifiedUser.roleName }}</p>
          </template>
        </el-alert>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { resetPassword, verifySecurityQuestion } from '@/api/auth'

export default {
  name: 'ForgotPassword',
  setup() {
    const router = useRouter()

    // 表单引用
    const verifyFormRef = ref(null)
    const resetFormRef = ref(null)
    const loading = ref(false)
    const currentStep = ref(0)
    const verifiedUser = ref(null)

    // 安全问题列表
    const securityQuestions = ref([
      { value: 'pet', label: '您的第一个宠物的名字是什么？' },
      { value: 'school', label: '您的小学名称是什么？' },
      { value: 'mother', label: '您母亲的姓名是什么？' },
      { value: 'born', label: '您的出生城市是哪里？' },
      { value: 'friend', label: '您最好朋友的名字是什么？' },
      { value: 'teacher', label: '您最喜欢的老师姓名是什么？' }
    ])

    // 身份验证表单数据
    const verifyForm = reactive({
      username: '',
      question: '',
      answer: ''
    })

    // 重置密码表单数据
    const resetForm = reactive({
      newPassword: '',
      confirmPassword: ''
    })

    // 身份验证表单规则
    const verifyRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      question: [
        { required: true, message: '请选择安全问题', trigger: 'change' }
      ],
      answer: [
        { required: true, message: '请输入安全问题的答案', trigger: 'blur' },
        { min: 2, max: 30, message: '答案长度在 2 到 30 个字符', trigger: 'blur' }
      ]
    }

    // 重置密码表单规则
    const resetRules = {
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
        { pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,20}$/, message: '密码必须包含字母和数字', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== resetForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 处理身份验证
    const handleVerify = async () => {
      if (!verifyFormRef.value) return

      try {
        // 表单验证
        await verifyFormRef.value.validate()

        loading.value = true

        // 验证用户名和安全问题答案
        const verifyData = {
          username: verifyForm.username,
          question: verifyForm.question,
          answer: verifyForm.answer
        }

        const response = await verifySecurityQuestion(verifyData)

        if (!response.data.success) {
          ElMessage.error(response.data.message || '安全问题答案错误')
          return
        }

        // 验证成功，保存用户信息
        verifiedUser.value = {
          username: response.data.username,
          realName: response.data.realName,
          roleName: response.data.roleName
        }

        ElMessage.success('身份验证成功')
        currentStep.value = 1

      } catch (error) {
        console.error('身份验证失败:', error)
        ElMessage.error('身份验证失败，请检查用户名和安全问题答案')
      } finally {
        loading.value = false
      }
    }

    // 处理密码重置
    const handleReset = async () => {
      if (!resetFormRef.value) return

      try {
        // 表单验证
        await resetFormRef.value.validate()

        loading.value = true

        // 调用重置密码接口
        const resetData = {
          username: verifyForm.username,
          newPassword: resetForm.newPassword,
          securityAnswer: verifyForm.answer
        }

        await resetPassword(resetData)

        ElMessage.success('密码重置成功，请使用新密码登录')

        // 延迟跳转到登录页面
        setTimeout(() => {
          router.push('/login')
        }, 1500)

      } catch (error) {
        console.error('密码重置失败:', error)
        ElMessage.error('密码重置失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    // 返回上一步
    const goBackStep = () => {
      currentStep.value = 0
      verifiedUser.value = null
      // 清空重置密码表单
      resetForm.newPassword = ''
      resetForm.confirmPassword = ''
    }

    // 返回登录页面
    const goBack = () => {
      router.push('/login')
    }

    return {
      verifyFormRef,
      resetFormRef,
      verifyForm,
      resetForm,
      verifyRules,
      resetRules,
      loading,
      currentStep,
      verifiedUser,
      securityQuestions,
      handleVerify,
      handleReset,
      goBackStep,
      goBack
    }
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-box {
  background: white;
  border-radius: 16px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 450px;
  backdrop-filter: blur(10px);
  position: relative;
}

.back-home {
  position: absolute;
  top: 20px;
  left: 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
  margin-top: 20px;
}

.login-header h2 {
  color: #333;
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.steps-container {
  margin-bottom: 30px;
}

.step-content {
  margin-bottom: 20px;
}

.login-form {
  margin-bottom: 20px;
}

.button-group {
  display: flex;
  gap: 12px;
  width: 100%;
}

.back-button {
  flex: 1;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  background: #f5f7fa;
  color: #606266;
  transition: all 0.3s ease;
}

.back-button:hover {
  background: #ecf5ff;
  color: #409eff;
  border-color: #c6e2ff;
}

.login-button {
  flex: 2;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.login-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.user-info {
  margin-top: 20px;
}

.user-info .el-alert {
  border-radius: 8px;
}

.user-info p {
  margin: 5px 0;
  font-size: 14px;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  padding: 0 15px;
  box-shadow: 0 0 0 1px #e4e7ed inset;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #667eea inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #667eea inset;
}

:deep(.el-form-item__error) {
  font-size: 12px;
  color: #f56c6c;
}

:deep(.el-steps--simple) {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 10px 20px;
}

:deep(.el-step__title.is-process) {
  color: #667eea;
  font-weight: 600;
}

:deep(.el-step__title.is-finish) {
  color: #67c23a;
}

:deep(.el-step__icon.is-process) {
  color: #667eea;
  border-color: #667eea;
}

:deep(.el-step__icon.is-finish) {
  color: #67c23a;
  border-color: #67c23a;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .login-box {
    padding: 30px 20px;
  }

  .login-header h2 {
    font-size: 24px;
  }

  .button-group {
    flex-direction: column;
  }

  .back-button,
  .login-button {
    width: 100%;
  }
}
</style>